<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-19
 * Time: 14:53
 */

namespace app\api\service\phone;

use app\api\model\Member;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\facade\Cache;

class ChangePhoneSer extends Token
{
    /**
     * 1.获取用户信息 判断用户信息
     * 2.判断手机号
     * 3.修改手机号
     */

    private $phone;

    private $code;

    private $user;

    function __construct($phone,$code)
    {
        $uid = self::getCurrentUid();
        $this->user = User::with('member')->where('id',$uid)->find();
        $this->phone = $phone;
        $this->code = $code;
    }

    // 登录验证短信验证码
    public function setSmsChange()
    {
        return $this->judgeMemberTwo();
    }

    // 判断会员信息
    private function judgeMemberTwo()
    {
        if(!$this->user['member']) {
            throw new ParameterException([
                'msg' => [
                    'tel' => '会员还未申请'
                ]
            ]);
        }
        return $this->judgeData();
    }

    // 判断信息
    private function judgeData()
    {
        $arr = Cache::get($this->user['id']);
        if($arr['phone'] != $this->phone) {
            throw new ParameterException([
                'msg' => [
                    'sms' => '手机号不同'
                ]
            ]);
        }
        if($arr['code'] != $this->code) {
            throw new ParameterException([
                'msg' => [
                    'sms' => '验证码错误'
                ]
            ]);
        }
        return $this->updateData($arr['phone']);
    }

    // 更新手机号
    private function updateData($phone)
    {
        Member::where('id',$this->user['member']['id'])->update([
            'phone' => $phone
        ]);
        return writeJson(202, [], '修改成功！');
    }
}